<template>
	<div class="indexBox">
		<div class="poundBox">
			<el-card class="poundCard">
				<el-row :gutter="20">
					<!-- 左侧磅房 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="pound-col left-pound"
						style="border-right: 1px dashed #CCC;padding: 10px; box-sizing: border-box;">
						<pound :weightOBJ="counterStore.eastPound"></pound>

						<div class="leftBox">
							<div class="leftBox_name">一磅计量单</div>
							<el-form :model="formAData" :rules="rules" ref="formARef" label-width="100px">
								<el-form-item label="过磅类型" prop="weighingType">
									<el-select style="width: 400px;" v-model="formAData.weighingType"
										placeholder="请选择过磅类型" @change="(val) => handleWeighingTypeChange('1001', Number(val))">
										<el-option v-for="item in options" :key="item.value" :label="item.label"
											:value="item.value" />
									</el-select>
								</el-form-item>

								<el-form-item label="车牌号码" prop="autoLicense">
									<el-input v-model="formAData.autoLicense" style="width: 400px;"
										placeholder="例：京A12345" @input="handleInput('1001',$event)" />
								</el-form-item>
								<el-form-item label="货物名称" prop="cargoName">
									<el-select v-model="formAData.cargoName" filterable allow-create
										default-first-option :reserve-keyword="false" placeholder="请输入或选择货物名称"
										style="width: 400px" @change="(val) => handleCargoChange(val, formAData)"
										value-key="id" clearable>
										<el-option v-for="item in cargoOptions" :key="item.cargoName"
											:label="item.cargoName" :value="item.cargoName">
											<span>{{ item.cargoName }}</span>
										</el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="发货厂家" prop="shippingCompanyId">
									<el-select v-model="formAData.shippingCompanyId" filterable default-first-option
										:reserve-keyword="false" placeholder="请选择发货厂家" style="width: 400px"
										value-key="id" clearable>
										<el-option v-for="item in caiOptions" :key="item.id" :label="item.companyName"
											:value="item.id">
											<span>{{ item.companyName }}</span>
										</el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="收货厂家" prop="receivingCompanyId">
									<el-select v-model="formAData.receivingCompanyId" filterable default-first-option
										:reserve-keyword="false" placeholder="请选择收货厂家" style="width: 400px"
										value-key="id" clearable>
										<el-option v-for="item in xiaoOptions" :key="item.id" :label="item.companyName"
											:value="item.id">
											<span>{{ item.companyName }}</span>
										</el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="规格" prop="specifications">
									<el-input v-model="formAData.specifications" style="width: 400px;" />
								</el-form-item>
								<el-form-item label="司机姓名" prop="driverName">
									<el-input v-model="formAData.driverName" style="width: 400px;" />
								</el-form-item>
								<el-form-item label="一次过磅(t)" prop="aWeight">
									<el-input-number v-model="formAData.aWeight" :min="0" :precision="2"
										style="width: 400px;" disabled />
								</el-form-item>
								<el-form-item label="二次过磅(t)" prop="secondWeight">
									<el-input-number v-model="formAData.secondWeight" :min="0" :precision="2"
										style="width: 400px;" disabled />
								</el-form-item>
								<!-- <el-form-item v-if="formAData.weightStatus===2" label="净重(kg)" prop="suttle">
									<el-input v-model="formAData.suttle" disabled style="width: 400px;" />
								</el-form-item> -->
								<div style="margin-top: 5px; display: flex;flex-direction:row-reverse;">
									<el-button type="primary"
										@click="handleFormAction(formARef, formAData, 'SUBMIT', '1001')">提交</el-button>
								</div>
							</el-form>
						</div>
					</el-col>

					<!-- 右侧磅房 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="pound-col right-pound"
						style="padding: 10px;box-sizing: border-box;">
						<pound :weightOBJ="counterStore.westPound"></pound>
						<div class="rightBox">
							<div class="rightBox_name">二磅计量单</div>
							<el-form :model="formBData" :rules="rules" ref="formBRef" label-width="100px">
								<el-form-item label="过磅类型" prop="weighingType">
									<el-select style="width: 400px;" v-model="formBData.weighingType"
										placeholder="请选择过磅类型" @change="(val) => handleWeighingTypeChange('1002', Number(val))">
										<el-option v-for="item in options" :key="item.value" :label="item.label"
											:value="item.value" />
									</el-select>
								</el-form-item>
								<el-form-item label="车牌号码" prop="autoLicense">
									<el-input v-model="formBData.autoLicense" placeholder="例：京A12345"
										style="width: 400px;" @input="handleInput('1002',$event)" />
								</el-form-item>

								<el-form-item label="货物名称" prop="cargoName">
									<el-select v-model="formBData.cargoName" filterable default-first-option
										:reserve-keyword="false" placeholder="请输入或选择货物名称" style="width: 400px"
										@change="(val) => handleCargoChange(val, formBData)" value-key="id" clearable>
										<el-option v-for="item in cargoOptions" :key="item.cargoName"
											:label="item.cargoName" :value="item.cargoName">
											<span>{{ item.cargoName }}</span>
										</el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="发货厂家" prop="shippingCompanyId">
									<el-select v-model="formBData.shippingCompanyId" filterable :reserve-keyword="false"
										placeholder="请选择发货厂家" style="width: 400px" value-key="id" clearable>
										<el-option v-for="item in caiOptions" :key="item.id" :label="item.companyName"
											:value="item.id">
											<span>{{ item.companyName }}</span>
										</el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="收货厂家" prop="receivingCompanyId">
									<el-select v-model="formBData.receivingCompanyId" filterable
										:reserve-keyword="false" placeholder="请选择收货厂家" style="width: 400px"
										value-key="id" clearable>
										<el-option v-for="item in xiaoOptions" :key="item.id" :label="item.companyName"
											:value="item.id">
											<span>{{ item.companyName }}</span>
										</el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="规格" prop="specifications">
									<el-input v-model="formBData.specifications" style="width: 400px;" />
								</el-form-item>
								<el-form-item label="司机姓名" prop="driverName">
									<el-input v-model="formBData.driverName" style="width: 400px;" />
								</el-form-item>
								<el-form-item label="一次过磅(t)" prop="aWeight">
									<el-input-number v-model="formBData.aWeight" :min="0" :precision="2"
										style="width: 400px;" disabled />
								</el-form-item>
								<el-form-item label="二次过磅(t)" prop="secondWeight">
									<el-input-number v-model="formBData.secondWeight" :min="0" :precision="2"
										style="width: 400px;" disabled />
								</el-form-item>
								<!-- <el-form-item v-if="formBData.weightStatus===2" label="净重(kg)" prop="suttle">
									<el-input v-model="formBData.suttle" disabled style="width: 400px;" />
								</el-form-item> -->
								<div style="margin-top: 5px; display: flex;flex-direction:row-reverse;">
									<el-button type="primary"
										@click="handleFormAction(formBRef, formBData, 'SUBMIT','1002')">提交</el-button>
								</div>
							</el-form>
						</div>
					</el-col>
				</el-row>
			</el-card>
		</div>
	</div>
</template>

<script setup lang="ts">
	import {
		ref,
		reactive,
		onMounted,
		nextTick,
		watch,
		onBeforeUnmount,
		getCurrentInstance,
		onActivated,
		toRaw
	} from 'vue';
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	const {
		proxy
	} = getCurrentInstance()
	import { useRouter } from 'vue-router'
	import type { FormInstance, FormRules } from 'element-plus'
	import pound from '@/components/pound/pound.vue'
	import poundDialog from '@/components/poundDialog/poundDialog.vue'
	import { debounce } from 'lodash-es'
	import { useCounterStore } from '@/stores/index'
	import { useLogout } from '@/utils/logout'

	const { logout } = useLogout()
	const counterStore = useCounterStore()
	interface CargoOption {
		cargoName : string
		id : string
		specifications ?: string
	}
	interface CompanyOption {
		companyName : string
		id : string
	}
	const cargoOptions = ref<CargoOption[]>([])
	const caiOptions = ref<CompanyOption[]>([])
	const xiaoOptions = ref<CompanyOption[]>([])
	const options = [
		{ label: '采购', value: 1 },
		{ label: '销售', value: 2 }
	]

	// 添加临时禁用实时更新的标记
	const disableRealtimeUpdate = ref({
		'1001': {
			status: false,
			reason: '' // 记录禁用原因：'history-loading' | 'manual-edit' | ''
		},
		'1002': {
			status: false,
			reason: ''
		}
	})

	// 统一缓存配置
	const CACHE_CONFIG = {
		getKey(loadCode : string) {
			return `weighing_form_${loadCode}`; // 缓存键前缀，避免冲突
		},
		expireTime: 24 * 60 * 60 * 1000, // 缓存有效期：24小时
	};

	// 缓存读取工具函数
	const getCacheData = (loadCode : string) => {
		const cacheKey = CACHE_CONFIG.getKey(loadCode);
		console.log('cacheKey',cacheKey)
		const cacheStr = localStorage.getItem(cacheKey);
		if (!cacheStr) return null;

		try {
			const cache = JSON.parse(cacheStr);
			// 判断缓存是否过期
			const isExpired = Date.now() - cache.timestamp > CACHE_CONFIG.expireTime;
			if (isExpired) {
				localStorage.removeItem(cacheKey);
				return null;
			}

			// 判断缓存数据是否有效
			const cacheData = cache.data;
			if (!cacheData || (!cacheData.autoLicense && cacheData.aWeight <= 0 && cacheData.secondWeight <= 0)) {
				localStorage.removeItem(cacheKey);
				return null;
			}

			return cacheData;
		} catch (error) {
			console.error(`读取${loadCode}磅缓存失败：`, error);
			localStorage.removeItem(cacheKey);
			return null;
		}
	};

	// 缓存保存工具函数 - 用户离开页面后回来读取缓存数据
	const saveFormCache = (loadCode : string, formData : WeighingFormData) => {
		try {
			const cacheKey = CACHE_CONFIG.getKey(loadCode);
			const cacheData = {
				data: { ...formData },
				timestamp: Date.now()
			};
			localStorage.setItem(cacheKey, JSON.stringify(cacheData));
			console.log(`${loadCode}磅表单缓存已保存`);
		} catch (error) {
			console.error(`保存${loadCode}磅缓存失败：`, error);
		}
	};

	// 先定义表单数据结构（关键：确保在watch之前定义）
	type WeighingStatus = 0 | 1 | 2

	interface WeighingFormData {
		id : number | null;
		autoLicense : string;
		cargoName : string;
		driverName : string;
		shippingCompanyId : string;
		receivingCompanyId : string;
		specifications : string;
		aWeight : number;
		secondWeight : number;
		suttle : number;
		weightStatus : number;
		deductingId : string;
		weighingType : number;
		// 用于存储历史数据，不会被实时数据覆盖
		historicalAWeight : number;
		historicalSecondWeight : number;
		// 标记是否已根据过磅类型调整过重量
		weightsAdjusted : boolean;
		// 记录实时数据应该推送到哪个字段
		realtimeTarget : 'aWeight' | 'secondWeight' | 'none';
		hasLoadedHistory : boolean;      // 新增：标记是否已加载历史数据
		isManualAdjust : boolean; // 标记是否手动调整过重量
		isLoadingHistory : boolean; // 标记是否正在加载历史数据
		// 前端自用字段，不发送给后端
		hasSubmittedFirstWeigh : boolean; // 标记是否已提交过一次过磅
		frontendWeighStatus : number; // 前端维护的称重状态，用于界面逻辑

	}

	// 地磅A配置（关键：提前定义，确保watch时已初始化）
	const formARef = ref<FormInstance>()
	const formAData = reactive<WeighingFormData>({
		id: null,
		autoLicense: '',
		cargoName: '',
		driverName: '',
		shippingCompanyId: '',
		receivingCompanyId: '',
		specifications: '',
		aWeight: 0,
		secondWeight: 0,
		suttle: 0,
		weightStatus: 0,
		deductingId: '',
		weighingType: 1,
		historicalAWeight: 0,
		historicalSecondWeight: 0,
		weightsAdjusted: false,
		realtimeTarget: 'aWeight',
		hasLoadedHistory: false, // 新增：初始未加载历史数据
		isManualAdjust: false,
		isLoadingHistory: false,
		hasSubmittedFirstWeigh: false, // 前端字段：标记是否已提交一次过磅
		frontendWeighStatus: 0 // 前端字段：维护的称重状态
	})

	// 地磅B配置（关键：提前定义，确保watch时已初始化）
	const formBRef = ref<FormInstance>()
	const formBData = reactive<WeighingFormData>({
		id: null,
		autoLicense: '',
		cargoName: '',
		driverName: '',
		shippingCompanyId: '',
		receivingCompanyId: '',
		specifications: '',
		aWeight: 0,
		secondWeight: 0,
		suttle: 0,
		weightStatus: 0,
		deductingId: '',
		weighingType: 1,
		historicalAWeight: 0,
		historicalSecondWeight: 0,
		weightsAdjusted: false,
		realtimeTarget: 'aWeight',
		hasLoadedHistory: false, // 新增：初始未加载历史数据
		isManualAdjust: false,
		isLoadingHistory: false,
		hasSubmittedFirstWeigh: false, // 前端字段：标记是否已提交一次过磅
		frontendWeighStatus: 0 // 前端字段：维护的称重状态
	})

	// 表单规则（放在表单数据后面定义）
	const rules = reactive<FormRules<WeighingFormData>>({
		autoLicense: [
			{ required: true, message: '请输入车牌号', trigger: 'blur' },
			{
				pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/,
				message: '请输入有效车牌号', trigger: 'blur'
			}
		],
		cargoName: [
			{ required: true, message: '请输入货物名称', trigger: 'blur' }
		],
		shippingCompanyId: [
			{ required: true, message: '请选择发货厂家', trigger: 'blur' },
		],
		receivingCompanyId: [
			{ required: true, message: '请选择收货厂家', trigger: 'blur' },
		],
		aWeight: [
			{ type: 'number', min: 0, message: '重量必须大于0', trigger: 'blur' }
		],
		secondWeight: [
			{ type: 'number', min: 0, message: '重量必须大于0', trigger: 'blur' }
		]
	})

	// 货物选择变化处理
	const handleCargoChange = (val : string, formData : Record<string, any>) => {
		// 查找匹配的货物项
		const matchingCargo = cargoOptions.value.find(
			(cargo) => formData.cargoName === cargo.cargoName
		);

		if (matchingCargo) {
			// 将匹配项的规格赋值给formData
			formData.specifications = matchingCargo.specifications;
		}

		// 检查货物是否已存在，不存在则添加
		if (!cargoOptions.value.some(item => item.cargoName === val)) {
			cargoOptions.value.push({
				cargoName: val,
				id: val,
			});
		}
	};

	const router = useRouter()

	const dongnum = ref(null)
	const xinum = ref(null)

	// 东磅实时数据监听逻辑 - 按业务需求重新设计
	watch(
		() => counterStore.eastPound,
		(newPoundData) => {
			
			// 实时更新禁用时，忽略更新
			if (disableRealtimeUpdate.value['1001'].status) {
				// console.log('东磅实时更新禁用，忽略实时数据更新');
				return;
			}

			// 确保有有效重量数据
			if (newPoundData.weight === undefined ) {
				return;
			}

			// 处理车牌号获取 - websocket推送或手动输入
			const incomingLicense = newPoundData.autoLicense;
			if (incomingLicense && incomingLicense !== formAData.autoLicense) {
				// console.log(`东磅：获取到新车牌号 ${incomingLicense}`);
				formAData.autoLicense = incomingLicense;
				// 获取车牌后立即查询历史数据
				checkLicensePlate('1001', incomingLicense, false);
				return; // 等待历史数据查询完成
			}

			// 详细状态日志
			// console.log(`东磅状态检查：hasLoadedHistory=${formAData.hasLoadedHistory}, historicalAWeight=${formAData.historicalAWeight}, aWeight=${formAData.aWeight}, secondWeight=${formAData.secondWeight}`);

			// 核心业务逻辑：根据是否有历史数据决定实时数据去向
			if (formAData.hasLoadedHistory && formAData.historicalAWeight > 0) {
				// 有历史数据：保存原始历史数据，智能分配显示位置
				// console.log(`东磅：有历史数据，实时重量${newPoundData.weight}t 进行智能分配`);
				
				// 确保原始历史数据被保存（如果还没保存的话）
				if (formAData.historicalAWeight === 0) {
					formAData.historicalAWeight = formAData.aWeight;
					// console.log(`东磅：保存原始历史一次过磅数据=${formAData.historicalAWeight}t`);
				}
				
				// 根据过磅类型决定重量的显示位置（不丢失原始数据）
				if (formAData.weighingType === 1) {
					// 采购：毛重 > 皮重
					const historyWeight = formAData.historicalAWeight;
					const realtimeWeight = newPoundData.weight;
					
					if (historyWeight > realtimeWeight) {
						// 历史数据是毛重，实时数据是皮重
						formAData.aWeight = historyWeight; // 一次过磅显示毛重
						formAData.secondWeight = realtimeWeight; // 二次过磅显示皮重
						// console.log(`东磅采购：历史毛重=${historyWeight}t，实时皮重=${realtimeWeight}t`);
					} else {
						// 实时数据是毛重，历史数据是皮重
						formAData.aWeight = realtimeWeight; // 一次过磅显示毛重
						formAData.secondWeight = historyWeight; // 二次过磅显示皮重
						// console.log(`东磅采购：实时毛重=${realtimeWeight}t，历史皮重=${historyWeight}t`);
					}
				} else if (formAData.weighingType === 2) {
					// 销售：皮重 < 毛重
					const historyWeight = formAData.historicalAWeight;
					const realtimeWeight = newPoundData.weight;
					
					if (historyWeight < realtimeWeight) {
						// 历史数据是皮重，实时数据是毛重
						formAData.aWeight = historyWeight; // 一次过磅显示皮重
						formAData.secondWeight = realtimeWeight; // 二次过磅显示毛重
						// console.log(`东磅销售：历史皮重=${historyWeight}t，实时毛重=${realtimeWeight}t`);
					} else {
						// 实时数据是皮重，历史数据是毛重
						formAData.aWeight = realtimeWeight; // 一次过磅显示皮重
						formAData.secondWeight = historyWeight; // 二次过磅显示毛重
						// console.log(`东磅销售：实时皮重=${realtimeWeight}t，历史毛重=${historyWeight}t`);
					}
				}
				formAData.frontendWeighStatus = 2; // 二次过磅完成（前端状态）
			} else {
				// 无历史数据或根据weightStatus状态处理实时数据
				// console.log(`东磅：处理实时数据，当前weightStatus=${formAData.weightStatus}，实时重量${newPoundData.weight}t`);
				
				if (formAData.weightStatus === 0) {
					// 未过磅状态：实时数据赋值给一次过磅
					formAData.aWeight = newPoundData.weight;
					formAData.secondWeight = 0; // 确保二次过磅为0
					// console.log(`东磅：未过磅状态 - 实时数据赋值给一次过磅=${formAData.aWeight}t，weightStatus=${formAData.weightStatus}`);
				} else if (formAData.weightStatus === 1) {
					// 一次过磅完成：实时数据赋值给二次过磅
					formAData.secondWeight = newPoundData.weight;
					// console.log(`东磅：一次过磅完成 - 实时数据赋值给二次过磅=${formAData.secondWeight}t，weightStatus=${formAData.weightStatus}`);
				} else if (formAData.weightStatus === 2) {
					// 二次过磅完成：忽略实时数据更新
					// console.log(`东磅：二次过磅已完成，忽略实时数据更新，weightStatus=${formAData.weightStatus}`);
				}
			}

			// 计算净重：只有在两次过磅都完成时才计算有效净重
			if (formAData.aWeight > 0 && formAData.secondWeight > 0) {
				formAData.suttle = Math.abs(formAData.aWeight - formAData.secondWeight) * 1000;
			} else {
				formAData.suttle = 0; // 第一次过磅时净重为0
			}

			// 保存缓存 - 用户离开页面后回来读取（只有有车牌号时才保存）
			if (formAData.autoLicense && formAData.autoLicense.trim()) {
				saveFormCache('1001', formAData);
			}
		},
		{ deep: true }
	);

	// 西磅实时数据监听逻辑 - 按业务需求重新设计
	watch(
		() => counterStore.westPound,
		(newPoundData) => {
			// 实时更新禁用时，忽略更新
			if (disableRealtimeUpdate.value['1002'].status) {
				console.log('西磅实时更新禁用，忽略实时数据更新');
				return;
			}

			// 确保有有效重量数据
			if (newPoundData.weight === undefined ) {
				return;
			}

			// 处理车牌号获取 - websocket推送或手动输入
			const incomingLicense = newPoundData.autoLicense;
			if (incomingLicense && incomingLicense !== formBData.autoLicense) {
				// console.log(`西磅：获取到新车牌号 ${incomingLicense}`);
				formBData.autoLicense = incomingLicense;
				// 获取车牌后立即查询历史数据
				checkLicensePlate('1002', incomingLicense, false);
				return; // 等待历史数据查询完成
			}

			// 详细状态日志
			// console.log(`西磅状态检查：hasLoadedHistory=${formBData.hasLoadedHistory}, historicalAWeight=${formBData.historicalAWeight}, aWeight=${formBData.aWeight}, secondWeight=${formBData.secondWeight}`);

			// 核心业务逻辑：根据是否有历史数据决定实时数据去向
			if (formBData.hasLoadedHistory && formBData.historicalAWeight > 0) {
				// 有历史数据：保存原始历史数据，智能分配显示位置
				// console.log(`西磅：有历史数据，实时重量${newPoundData.weight}t 进行智能分配`);
				
				// 确保原始历史数据被保存（如果还没保存的话）
				if (formBData.historicalAWeight === 0) {
					formBData.historicalAWeight = formBData.aWeight;
					// console.log(`西磅：保存原始历史一次过磅数据=${formBData.historicalAWeight}t`);
				}
				
				// 根据过磅类型决定重量的显示位置（不丢失原始数据）
				if (formBData.weighingType === 1) {
					// 采购：毛重 > 皮重
					const historyWeight = formBData.historicalAWeight;
					const realtimeWeight = newPoundData.weight;
					
					if (historyWeight > realtimeWeight) {
						// 历史数据是毛重，实时数据是皮重
						formBData.aWeight = historyWeight; // 一次过磅显示毛重
						formBData.secondWeight = realtimeWeight; // 二次过磅显示皮重
						// console.log(`西磅采购：历史毛重=${historyWeight}t，实时皮重=${realtimeWeight}t`);
					} else {
						// 实时数据是毛重，历史数据是皮重
						formBData.aWeight = realtimeWeight; // 一次过磅显示毛重
						formBData.secondWeight = historyWeight; // 二次过磅显示皮重
						// console.log(`西磅采购：实时毛重=${realtimeWeight}t，历史皮重=${historyWeight}t`);
					}
				} else if (formBData.weighingType === 2) {
					// 销售：皮重 < 毛重
					const historyWeight = formBData.historicalAWeight;
					const realtimeWeight = newPoundData.weight;
					
					if (historyWeight < realtimeWeight) {
						// 历史数据是皮重，实时数据是毛重
						formBData.aWeight = historyWeight; // 一次过磅显示皮重
						formBData.secondWeight = realtimeWeight; // 二次过磅显示毛重
						// console.log(`西磅销售：历史皮重=${historyWeight}t，实时毛重=${realtimeWeight}t`);
					} else {
						// 实时数据是皮重，历史数据是毛重
						formBData.aWeight = realtimeWeight; // 一次过磅显示皮重
						formBData.secondWeight = historyWeight; // 二次过磅显示毛重
						// console.log(`西磅销售：实时皮重=${realtimeWeight}t，历史毛重=${historyWeight}t`);
					}
				}
				formBData.frontendWeighStatus = 2; // 二次过磅完成（前端状态）
			} else {
				// 无历史数据或根据weightStatus状态处理实时数据
				// console.log(`西磅：处理实时数据，当前weightStatus=${formBData.weightStatus}，实时重量${newPoundData.weight}t`);
				
				if (formBData.weightStatus === 0) {
					// 未过磅状态：实时数据赋值给一次过磅
					formBData.aWeight = newPoundData.weight;
					formBData.secondWeight = 0; // 确保二次过磅为0
					// console.log(`西磅：未过磅状态 - 实时数据赋值给一次过磅=${formBData.aWeight}t，weightStatus=${formBData.weightStatus}`);
				} else if (formBData.weightStatus === 1) {
					// 一次过磅完成：实时数据赋值给二次过磅
					formBData.secondWeight = newPoundData.weight;
					// console.log(`西磅：一次过磅完成 - 实时数据赋值给二次过磅=${formBData.secondWeight}t，weightStatus=${formBData.weightStatus}`);
				} else if (formBData.weightStatus === 2) {
					// 二次过磅完成：忽略实时数据更新
					// console.log(`西磅：二次过磅已完成，忽略实时数据更新，weightStatus=${formBData.weightStatus}`);
				}
			}

			// 计算净重：只有在两次过磅都完成时才计算有效净重
			if (formBData.aWeight > 0 && formBData.secondWeight > 0) {
				formBData.suttle = Math.abs(formBData.aWeight - formBData.secondWeight) * 1000;
			} else {
				formBData.suttle = 0; // 第一次过磅时净重为0
			}

			// 保存缓存 - 用户离开页面后回来读取（只有有车牌号时才保存）
			if (formBData.autoLicense && formBData.autoLicense.trim()) {
				saveFormCache('1002', formBData);
			}
		},
		{ deep: true }
	);
	// 3. 修复：查询历史数据逻辑（解决销售/采购类型重量赋值）
	const checkLicensePlate = async (loadCode : string, cardCode : string, isManualInput : boolean = false) => {
		let targetForm : WeighingFormData = loadCode === '1001' ? formAData : formBData;

		try {
			const upperCardCode = cardCode.toUpperCase();
			if (upperCardCode.length < 3) {
				console.log(`车牌号"${upperCardCode}"长度不足3位，跳过查询`);
				return;
			}

			if (targetForm.isLoadingHistory) {
				console.log(`正在加载${loadCode}磅历史数据，忽略重复请求`);
				return;
			}

			disableRealtimeUpdate.value[loadCode] = { status: true, reason: 'history-loading' };
			targetForm.isLoadingHistory = true;
			console.log(`开始查询${loadCode}磅历史数据: ${upperCardCode}`);

			const res = await proxy.$request.weighFeedback({ autoLicense: upperCardCode });

			if (res?.data?.code === 200) {
				ElMessage.success(res?.data?.message);
				if (res.data.result) {
					const historyData : WeighingHistory = res.data.result;

					// 保存历史原始重量
					targetForm.historicalAWeight = historyData.aWeight || 0;
					targetForm.historicalSecondWeight = historyData.secondWeight || 0;

					// 复制非重量字段
					Object.keys(historyData).forEach(key => {
						if (!['aWeight', 'secondWeight', 'suttle', 'weightStatus', 'realtimeTarget', 'isManualAdjust'].includes(key)) {
							if (key === 'autoLicense' && isManualInput) return;
							targetForm[key] = historyData[key] || '';
						}
					});

					// 智能重量位置分配：根据过磅类型和历史状态正确放置重量
					if (historyData.weightStatus === 0 || (historyData.aWeight || 0) === 0) {
						// 未过磅状态或第一次重量为0 - 按无历史数据处理
						targetForm.aWeight = 0;
						targetForm.secondWeight = 0;
						targetForm.suttle = 0;
						targetForm.frontendWeighStatus = 0; // 同步前端状态字段
						targetForm.realtimeTarget = 'aWeight';
						targetForm.hasLoadedHistory = false; // 关键：标记为无有效历史数据
						targetForm.historicalAWeight = 0;
						console.log(`${loadCode}磅：历史数据无有效过磅重量，按新车辆处理，等待实时数据`);
					} else if (historyData.weightStatus === 1) {
						// 一次过磅完成 - 需要根据当前过磅类型智能分配位置
						const historyWeight = historyData.aWeight || 0;
						
						// 重要修复：不管历史数据如何存储，都将一次过磅重量放在aWeight
						// 因为实时的二次过磅会更新secondWeight
						targetForm.aWeight = historyWeight;
						targetForm.secondWeight = 0;
						// 关键：设置weightStatus为历史查询接口返回的值
						targetForm.weightStatus = historyData.weightStatus;
						targetForm.frontendWeighStatus = historyData.weightStatus; // 同步后端状态到前端字段
						targetForm.realtimeTarget = 'secondWeight'; // 等待二次过磅实时数据
						targetForm.hasLoadedHistory = true; // 标记有有效历史数据
						targetForm.historicalAWeight = historyWeight; // 保存原始历史数据
						console.log(`历史数据一次过磅完成：一次重量=${historyWeight}t，二次重量=0，等待实时数据更新二次过磅`);
					} else if (historyData.weightStatus === 2) {
						// 二次过磅完成 - 根据当前过磅类型调整重量位置
						let aWeight = historyData.aWeight || 0;
						let secondWeight = historyData.secondWeight || 0;
						
						// 根据当前表单的过磅类型重新调整重量位置
						if (targetForm.weighingType === 1) {
							// 采购：确保aWeight > secondWeight (毛重 > 皮重)
							if (aWeight < secondWeight) {
								[aWeight, secondWeight] = [secondWeight, aWeight];
								console.log(`采购模式：调整重量位置 ${historyData.aWeight} ↔ ${historyData.secondWeight}`);
							}
						} else if (targetForm.weighingType === 2) {
							// 销售：确保aWeight < secondWeight (皮重 < 毛重)  
							if (aWeight > secondWeight) {
								[aWeight, secondWeight] = [secondWeight, aWeight];
								console.log(`销售模式：调整重量位置 ${historyData.aWeight} ↔ ${historyData.secondWeight}`);
							}
						}
						
						targetForm.aWeight = aWeight;
						targetForm.secondWeight = secondWeight;
						// 关键：设置weightStatus为历史查询接口返回的值
						targetForm.weightStatus = historyData.weightStatus;
						targetForm.frontendWeighStatus = historyData.weightStatus; // 同步后端状态到前端字段
						targetForm.hasLoadedHistory = true; // 标记有有效历史数据
						targetForm.historicalAWeight = aWeight; // 保存原始历史数据
						console.log(`历史数据二次过磅完成：一次=${aWeight}t，二次=${secondWeight}t`);
					}

					// 暂时禁用重量调整，避免覆盖历史数据
					// adjustWeightsForWeighingType(targetForm, loadCode);
					targetForm.weightsAdjusted = true;
				} else {
					// 无历史数据时的初始化（核心修复）
					console.log(`${loadCode}磅：无历史数据，初始化表单状态`);
					
					// 强制重置所有重量相关字段
					targetForm.aWeight = 0;
					targetForm.secondWeight = 0;
					targetForm.suttle = 0;
					targetForm.frontendWeighStatus = 0;
					targetForm.realtimeTarget = 'aWeight';
					targetForm.hasLoadedHistory = false;
					targetForm.isManualAdjust = false;
					targetForm.historicalAWeight = 0;
					targetForm.historicalSecondWeight = 0;
					
					console.log(`${loadCode}磅：等待实时数据进行第一次过磅`);
				}

				// 更新缓存
				localStorage.setItem(CACHE_CONFIG.getKey(loadCode), JSON.stringify({
					data: { ...targetForm },
					timestamp: Date.now()
				}));
			} else {
				// 查询历史数据失败（如"暂无过磅计划"），但仍需要给用户赋值车牌号
				console.log(`${loadCode}磅：查询历史数据失败，但给用户赋值车牌号: ${upperCardCode}`);
				targetForm.autoLicense = upperCardCode;
				
				// 初始化表单为新车辆状态
				targetForm.aWeight = 0;
				targetForm.secondWeight = 0;
				targetForm.suttle = 0;
				targetForm.weightStatus = 0;
				targetForm.frontendWeighStatus = 0;
				targetForm.realtimeTarget = 'aWeight';
				targetForm.hasLoadedHistory = false;
				targetForm.isManualAdjust = false;
				targetForm.historicalAWeight = 0;
				
				// 提示用户但不显示错误
				ElMessage.info(res?.data?.message || '暂无过磅计划，可进行新的称重');
			}
		} catch (error : any) {
			console.error('查询历史数据出错:', error);
			ElMessage.error(error.data?.message || '网络请求异常');
		} finally {
			// 延迟恢复实时数据更新，给历史数据足够时间稳定
			setTimeout(() => {
				disableRealtimeUpdate.value[loadCode] = { status: false, reason: '' };
				targetForm.isLoadingHistory = false;
				// 确保保护机制正常工作
				if (targetForm.hasLoadedHistory && targetForm.frontendWeighStatus === 1) {
					targetForm.realtimeTarget = 'secondWeight';
					console.log(`${loadCode}磅历史数据保护机制激活：realtimeTarget设置为secondWeight`);
				}
				console.log(`${loadCode}磅历史数据加载完成，恢复实时数据接收`);
			}, 500); // 延长延迟到500ms确保数据稳定
		}
	};
	// 获取货物列表
	const getCargoNameList = async () => {
		try {
			const res = await proxy.$request.getCargoNameList()
			cargoOptions.value = []
			if (res?.data?.code === 200 && res.data.result) {
				cargoOptions.value = res.data.result
			} else {
				ElMessage.error(res?.data?.message || '请求失败')
			}
		} catch (error : any) {
			console.error('API请求错误:', error)
			ElMessage.error(error.data.message || '网络请求异常')
		}
	}

	// 获取厂家列表
	const getCompanyNameList = async (num) => {
		try {
			const res = await proxy.$request.getCompanySelect({ companyType: num })
			if (res?.data?.code === 200 && res.data.result) {
				if (num === 1) {
					caiOptions.value = res.data.result
				}
				if (num === 2) {
					xiaoOptions.value = res.data.result
				}
			} else {
				ElMessage.error(res?.data?.message || '请求失败')
			}
		} catch (error : any) {
			console.error('API请求错误:', error)
			ElMessage.error(error.data.message || '网络请求异常')
		}
	}

	// 防抖函数
	function debounceFunc(func, wait) {
		let timeout;
		return function executedFunction(...args) {
			const later = () => {
				clearTimeout(timeout);
				func(...args);
			};
			clearTimeout(timeout);
			timeout = setTimeout(later, wait);
		};
	}

	// 处理车牌输入

	// 处理车牌输入 - 使用lodash的debounce确保防抖生效
	const handleInput = debounce(function (loadCode, value) {
		const trimmedValue = value.trim();

		// 核心新增：如果车牌号为空 → 重置表单+清除缓存
		if (!trimmedValue) {
			resetPoundForm(loadCode); // 调用上面定义的重置函数
			return; // 终止后续逻辑（无需查询历史数据）
		}

		// 原有逻辑：车牌号非空时的处理（保持不变）
		const upperValue = trimmedValue.toUpperCase();
		const targetForm = loadCode === '1001' ? formAData : formBData;

		// 保留用户手动输入的车牌
		targetForm.autoLicense = upperValue;
		localStorage.removeItem(CACHE_CONFIG.getKey(loadCode));

		// 短于3个字符不触发查询
		if (upperValue.length < 3) {
			console.log(`车牌号“${upperValue}”过短，暂不查询历史数据`);
			return;
		}

		// 仅当车牌长度≥3时，才触发历史查询
		checkLicensePlate(loadCode, upperValue, true);
	}, 2000); // 2秒防抖

	// 检查车牌历史数据
	interface WeighingHistory {
		id : number;
		autoLicense : string;
		cargoName : string;
		driverName : string;
		shippingCompanyId : string;
		receivingCompanyId : string;
		specifications : string;
		aWeight : number;
		secondWeight : number;
		suttle : number;
		weightStatus : number;
		deductingId : string;
		weighingType : number;
	}




	// 4. 修复：过磅类型切换重量调整逻辑（严格保证采购/销售重量顺序）
	const adjustWeightsForWeighingType = async (formData: WeighingFormData, loadCode: string) => {
	    // 1. 基础校验（保留）
	    console.log(`[${loadCode}] 开始交换：当前重量(a=${formData.aWeight}, b=${formData.secondWeight})，类型=${formData.weighingType===1?'采购':'销售'}`);
	    if (formData.aWeight <= 0 || formData.secondWeight <= 0) {
	        ElMessage.warning(`两次重量必须>0（a=${formData.aWeight}t, b=${formData.secondWeight}t）`);
	        return;
	    }
	
	    // 2. 核心交换逻辑（保留）
	    const originalA = formData.aWeight;
	    const originalB = formData.secondWeight;
	    let newA = originalA;
	    let newB = originalB;
		
	    if (formData.weighingType === 1 && originalA <= originalB) {
	        [newA, newB] = [originalB, originalA]; // 采购：a必须>b
	    } else if (formData.weighingType === 2 && originalA >= originalB) {
	        [newA, newB] = [originalB, originalA]; // 销售：a必须<b
	    }
	
	    // 3. 关键修复：交换后设置正确的状态，避免实时数据乱覆盖
	    formData.aWeight = newA;
	    formData.secondWeight = newB;
	    formData.suttle = Math.abs(newA - newB) * 1000;
		
	    
	    // 修复重点：根据交换后的重量状态，重置realtimeTarget（告诉实时数据该更哪个字段）
	    if (newA > 0 && newB <= 0) {
	        formData.frontendWeighStatus = 1; // 只有一次重量（前端状态）
	        formData.realtimeTarget = 'secondWeight'; // 下次实时数据更新二次
	    } else if (newA <= 0 && newB > 0) {
	        formData.frontendWeighStatus = 1; // 只有二次重量（异常，强制移到一次）（前端状态）
	        formData.aWeight = newB;
	        formData.secondWeight = 0;
	        formData.realtimeTarget = 'secondWeight';
	    } else if (newA > 0 && newB > 0) {
	        formData.frontendWeighStatus = 2; // 两次都有重量（前端状态）
	        // 保持实时数据接收能力，允许重新开始新一轮称重
	        console.log('重量调整完成，两次重量都有数据，保持实时数据接收能力');
	    }
	
	    // 4. 强制DOM更新（保留）
	    await nextTick();
	    console.log(`[${loadCode}] 交换完成：新重量(a=${newA}, b=${newB})，realtimeTarget=${formData.realtimeTarget}`);
	
	    // 5. 反馈结果（保留）
	    if (newA !== originalA) {
	        ElMessage.success(`[${loadCode}磅] 重量交换成功：${originalA}t ↔ ${originalB}t`);
	    } else {
	        ElMessage.info(`[${loadCode}磅] 重量已符合规则，无需交换`);
	    }
	};
	// 监听磅单数据变化（放在表单数据定义之后）
	watch(
		() => formAData,
		(newFormData) => {
			if (newFormData.autoLicense || newFormData.cargoName || newFormData.aWeight > 0) {
				const cacheKey = CACHE_CONFIG.getKey('1001');
				const cacheData = {
					data: { ...newFormData },
					timestamp: Date.now(),
				};
				localStorage.setItem(cacheKey, JSON.stringify(cacheData));
			}
		},
		{ deep: true, immediate: false }
	);

	watch(
		() => formBData,
		(newFormData) => {
			if (newFormData.autoLicense || newFormData.cargoName || newFormData.aWeight > 0) {
				const cacheKey = CACHE_CONFIG.getKey('1002');
				const cacheData = {
					data: { ...newFormData },
					timestamp: Date.now(),
				};
				localStorage.setItem(cacheKey, JSON.stringify(cacheData));
			}
		},
		{ deep: true, immediate: false }
	);
	watch(
		() => formAData.weighingType,
		(newVal, oldVal) => {
			// 禁用自动调整重量，只记录日志
			if (newVal === oldVal || oldVal === undefined || formAData.isManualAdjust) {
				return;
			}
			console.log('A磅过磅类型变化:', oldVal, '→', newVal, '（不自动调整重量，等待用户手动调整）');
			// 注释掉自动调整：
			// adjustWeightsForWeighingType(formAData, '1001');
			// 同步缓存
			nextTick(() => {
				localStorage.setItem(CACHE_CONFIG.getKey('1001'), JSON.stringify({
					data: { ...formAData },
					timestamp: Date.now()
				}));
			});
		}
	);

	// B磅weighingType监听（修改后）
	watch(
		() => formBData.weighingType,
		(newVal, oldVal) => {
			// 禁用自动调整重量，只记录日志
			if (newVal === oldVal || oldVal === undefined || formBData.isManualAdjust) {
				return;
			}
			console.log('B磅过磅类型变化:', oldVal, '→', newVal, '（不自动调整重量，等待用户手动调整）');
			// 注释掉自动调整：
			// adjustWeightsForWeighingType(formBData, '1002');
			nextTick(() => {
				localStorage.setItem(CACHE_CONFIG.getKey('1002'), JSON.stringify({
					data: { ...formBData },
					timestamp: Date.now()
				}));
			});
		}
	);

	// 过磅状态变化监听（放在表单数据定义之后）
	watch(
		() => formAData.weightStatus,
		(newStatus) => {
			console.log('A磅过磅状态变化:', newStatus);
			if (newStatus === 0) {
				formAData.realtimeTarget = 'aWeight';
			} else if (newStatus === 1) {
				formAData.realtimeTarget = 'secondWeight';
			} else if (newStatus === 2) {
				// 保持当前target，允许重新开始新一轮称重
				console.log('A磅：二次过磅完成，保持实时数据接收能力');
			}
			localStorage.setItem(CACHE_CONFIG.getKey('1001'), JSON.stringify({
				data: { ...formAData },
				timestamp: Date.now()
			}));
		}
	);

	watch(
		() => formBData.weightStatus,
		(newStatus) => {
			console.log('B磅过磅状态变化:', newStatus);
			if (newStatus === 0) {
				formBData.realtimeTarget = 'aWeight';
			} else if (newStatus === 1) {
				formBData.realtimeTarget = 'secondWeight';
			} else if (newStatus === 2) {
				// 保持当前target，允许重新开始新一轮称重
				console.log('B磅：二次过磅完成，保持实时数据接收能力');
			}
			localStorage.setItem(CACHE_CONFIG.getKey('1002'), JSON.stringify({
				data: { ...formBData },
				timestamp: Date.now()
			}));
		}
	);

	// 持久化车牌变化监听（关键：放在表单数据定义之后，解决初始化顺序问题）
	watch(
		() => counterStore.persistedData.licensePlates['1001'],
		(newLicense, oldLicense) => {
			// 新车牌且与当前表单车牌不一致时，查询历史数据
			if (newLicense && newLicense !== oldLicense && newLicense !== formAData.autoLicense) {
				console.log('-----------------')
				checkLicensePlate('1001', newLicense);
			}
		},
		{ immediate: true } // 初始化时也检查一次
	);

	watch(
		() => counterStore.persistedData.licensePlates['1002'],
		(newLicense, oldLicense) => {
			if (newLicense && newLicense !== oldLicense && newLicense !== formBData.autoLicense) {
				checkLicensePlate('1002', newLicense);
			}
		},
		{ immediate: true }
	);
	const resetPoundForm = (loadCode : string) => {
		const targetForm : WeighingFormData = loadCode === '1001' ? formAData : formBData;

		// 1. 清空核心表单字段（按 WeighingFormData 结构重置）
		targetForm.id = null;
		targetForm.autoLicense = ''; // 车牌号（核心清空项）
		targetForm.cargoName = ''; // 货物名称
		targetForm.driverName = ''; // 司机姓名
		targetForm.shippingCompanyId = ''; // 发货厂家
		targetForm.receivingCompanyId = ''; // 收货厂家
		targetForm.specifications = ''; // 规格
		targetForm.aWeight = 0; // 一次过磅重量
		targetForm.secondWeight = 0; // 二次过磅重量
		targetForm.suttle = 0; // 净重
		targetForm.weightStatus = 0; // 过磅状态（后端字段）
		targetForm.frontendWeighStatus = 0; // 过磅状态（前端状态）
		targetForm.deductingId = ''; // 扣重ID
		targetForm.weighingType = 1; // 默认过磅类型（采购）

		// 2. 重置辅助状态字段
		targetForm.historicalAWeight = 0; // 历史一次重量
		targetForm.historicalSecondWeight = 0; // 历史二次重量
		targetForm.weightsAdjusted = false; // 重量是否已调整
		targetForm.realtimeTarget = 'aWeight'; // 实时数据目标字段
		targetForm.hasLoadedHistory = false; // 是否加载过历史数据
		targetForm.isManualAdjust = false; // 是否手动调整
		targetForm.isLoadingHistory = false; // 是否正在加载历史数据

		// 3. 清除对应磅房的缓存
		const cacheKey = CACHE_CONFIG.getKey(loadCode);
		localStorage.removeItem(cacheKey);
		console.log(`已清空${loadCode}磅表单数据及缓存`);
	};

	// 处理过磅类型变更 - 使用原始历史数据进行重新分配
	const handleWeighingTypeChange = async (loadCode: string, newType: number) => {
	    const targetForm: WeighingFormData = loadCode === '1001' ? formAData : formBData;
	    const oldType = Number(targetForm.weighingType);
	    newType = Number(newType);
	
	    console.log(`[${loadCode}] 手动切换过磅类型：${oldType}→${newType}`);
	    console.log(`[${loadCode}] 当前显示重量：aWeight=${targetForm.aWeight}，secondWeight=${targetForm.secondWeight}`);
	    console.log(`[${loadCode}] 原始历史数据：historicalAWeight=${targetForm.historicalAWeight}`);
	
	    // 仅处理有效切换
	    if (oldType === newType || ![1, 2].includes(newType)) {
	        return;
	    }
	
	    // 阻断实时数据更新，防止干扰
	    disableRealtimeUpdate.value[loadCode] = { status: true, reason: 'manual-type-switch' };
	    targetForm.isManualAdjust = true;
	
	    try {
	        // 更新过磅类型
	        targetForm.weighingType = newType;
	        await nextTick();
	
	        // 核心修复：使用原始历史数据进行重量调整
	        if (targetForm.historicalAWeight > 0) {
	            console.log(`[${loadCode}] 使用原始历史数据进行重量调整`);
	            
	            // 获取当前实时重量（用于二次过磅）
	            const currentRealtimeWeight = loadCode === '1001' 
	                ? counterStore.eastPound.weight 
	                : counterStore.westPound.weight;
	            
	            // 根据新的过磅类型重新分配重量位置
	            if (newType === 1) {
					console.log('到这了')
	                // 采购模式：毛重 > 皮重
	                if (targetForm.historicalAWeight > currentRealtimeWeight && currentRealtimeWeight > 0) {
	                    // 原始历史数据是毛重，实时数据是皮重
	                    targetForm.aWeight = targetForm.historicalAWeight; // 一次过磅=毛重
	                    targetForm.secondWeight = currentRealtimeWeight;   // 二次过磅=皮重
	                    console.log(`[${loadCode}] 采购模式：历史毛重=${targetForm.historicalAWeight}，实时皮重=${currentRealtimeWeight}`);
	                } else if (targetForm.historicalAWeight < currentRealtimeWeight && currentRealtimeWeight > 0) {
	                    // 原始历史数据是皮重，实时数据是毛重
	                    targetForm.aWeight = currentRealtimeWeight;        // 一次过磅=毛重
	                    targetForm.secondWeight = targetForm.historicalAWeight; // 二次过磅=皮重
	                    console.log(`[${loadCode}] 采购模式：实时毛重=${currentRealtimeWeight}，历史皮重=${targetForm.historicalAWeight}`);
	                } else {
	                    // 只有历史数据，保持原始位置
	                    targetForm.aWeight = targetForm.historicalAWeight;
	                    targetForm.secondWeight = 0;
	                    console.log(`[${loadCode}] 采购模式：仅历史数据=${targetForm.historicalAWeight}`);
	                }
	            } else if (newType === 2) {
					console.log('到这了11')
	                // 销售模式：皮重 < 毛重
	                if (targetForm.historicalAWeight < currentRealtimeWeight && currentRealtimeWeight > 0) {
	                    // 原始历史数据是皮重，实时数据是毛重
	                    targetForm.aWeight = targetForm.historicalAWeight; // 一次过磅=皮重
	                    targetForm.secondWeight = currentRealtimeWeight;   // 二次过磅=毛重
	                    console.log(`[${loadCode}] 销售模式：历史皮重=${targetForm.historicalAWeight}，实时毛重=${currentRealtimeWeight}`);
	                } else if (targetForm.historicalAWeight > currentRealtimeWeight && currentRealtimeWeight > 0) {
	                    // 原始历史数据是毛重，实时数据是皮重
	                    targetForm.aWeight = currentRealtimeWeight;        // 一次过磅=皮重
	                    targetForm.secondWeight = targetForm.historicalAWeight; // 二次过磅=毛重
	                    console.log(`[${loadCode}] 销售模式：实时皮重=${currentRealtimeWeight}，历史毛重=${targetForm.historicalAWeight}`);
	                } else {
	                    // 只有历史数据，保持原始位置
	                    targetForm.aWeight = targetForm.historicalAWeight;
	                    targetForm.secondWeight = 0;
	                    console.log(`[${loadCode}] 销售模式：仅历史数据=${targetForm.historicalAWeight}`);
	                }
	            }
	
	            // 更新过磅状态
	            if (targetForm.aWeight > 0 && targetForm.secondWeight > 0) {
	                targetForm.frontendWeighStatus = 2; // 二次过磅完成（前端状态）
	                targetForm.realtimeTarget = 'none'; // 暂停接收实时数据
	            } else if (targetForm.aWeight > 0) {
	                targetForm.frontendWeighStatus = 1; // 一次过磅完成（前端状态）
	                targetForm.realtimeTarget = 'secondWeight'; // 等待二次过磅
	            }
	
	            // 计算净重
	            targetForm.suttle = Math.abs(targetForm.aWeight - targetForm.secondWeight) * 1000;
	            
	            console.log(`[${loadCode}] 重量调整完成：aWeight=${targetForm.aWeight}，secondWeight=${targetForm.secondWeight}，净重=${targetForm.suttle}kg`);
	            ElMessage.success(`[${loadCode}磅] 过磅类型切换完成，原始历史数据已保留`);
	        } else {
	            console.log(`[${loadCode}] 无原始历史数据，使用当前显示值进行调整`);
	            // 没有原始历史数据时，使用当前显示的重量值进行调整
	            await adjustWeightsForWeighingType(targetForm, loadCode);
	        }
	
	        // 保存缓存
	        localStorage.setItem(CACHE_CONFIG.getKey(loadCode), JSON.stringify({
	            data: { ...targetForm },
	            timestamp: Date.now()
	        }));
	        
	    } catch (error) {
	        console.error(`[${loadCode}] 切换过磅类型出错：`, error);
	        ElMessage.error('切换过磅类型失败');
	    } finally {
	        // 延迟恢复实时数据更新
	        setTimeout(() => {
	            targetForm.isManualAdjust = false;
	            disableRealtimeUpdate.value[loadCode] = { status: false, reason: '' };
	            targetForm.hasLoadedHistory = true;
	            console.log(`[${loadCode}] 过磅类型切换完成，实时数据更新已恢复`);
	        }, 200);
	    }
	};
	    

	// 处理表单提交
	const handleFormAction = async (
		formRef : FormInstance | undefined,
		formData : WeighingFormData,
		action : 'SUBMIT' | 'RESET',
		code : String
	) => {
		console.log('formData', formData)
		if (!formRef) return

		if (action === 'SUBMIT') {
			try {
				await formRef.validate()
				setWeighFeed(formRef, formData, code)
			} catch (e) {
				ElMessage.error('表单验证失败')
			}
		}
	}

	// 提交过磅数据
	const setWeighFeed = async (formRef, formData, num) => {
		try {
			// 验证提交数据的完整性（不修改weightStatus，只做验证）
			if (formData.aWeight === 0 && formData.secondWeight === 0) {
				ElMessage.error('请完成称重后再提交!');
				return;
			}
			
			if (formData.aWeight === 0) {
				ElMessage.error('一次过磅重量不能为0！');
				return;
			}

			// 确定当前实际提交状态（用于界面逻辑判断，不修改weightStatus）
			const currentSubmitStatus = formData.aWeight > 0 && formData.secondWeight > 0 ? 2 : 1;

			const matchingCargo = cargoOptions.value.find(
				(cargo) => cargo.cargoName === formData.cargoName
			);

			const deductingId = matchingCargo?.id === matchingCargo?.cargoName ? 0 : matchingCargo?.id;

			const res = await proxy.$request.setWeighFeed({
				autoLicense: formData.autoLicense,
				cargoName: formData.cargoName,
				shippingCompanyId: formData.shippingCompanyId,
				receivingCompanyId: formData.receivingCompanyId,
				weightStatus: formData.weightStatus,
				secondWeight: formData.secondWeight,
				aWeight: formData.aWeight,
				specifications: formData.specifications,
				driverName: formData.driverName,
				id: formData.id,
				deductingId: deductingId,
				weighingType: formData.weighingType
			})
			

			if (res?.data?.code === 200) {
				// 先保存车牌号用于清理历史缓存
				const currentLicense = formData.autoLicense;
				
				// 一次过磅和二次过磅提交成功后都清空表单
				formRef.resetFields()
				
				Object.assign(formData, {
					id: '',
					autoLicense: '',
					cargoName: '',
					shippingCompanyId: '',
					receivingCompanyId: '',
					weightStatus: 0, // 提交完成后重置为0，准备接收新车辆
					secondWeight: 0,
					aWeight: 0,
					specifications: '',
					driverName: '',
					suttle: 0,
					weighingType: 1,
					isManualAdjust: false,
					historicalAWeight: 0,
					hasSubmittedFirstWeigh: false,
					frontendWeighStatus: 0
				})
				
				// 提交成功后删除缓存
				localStorage.removeItem(CACHE_CONFIG.getKey(num))
				localStorage.removeItem(num)
				counterStore.persistedData.licensePlates[num]=''
				const historyKey = `history_${currentLicense}`
		
				localStorage.removeItem(historyKey)
				
				
				// 清空历史数据缓存（使用保存的车牌号）
				// if (currentLicense) {
				// 	console.log('currentLicense',currentLicense)
				// 	const historyKey = `history_${currentLicense}`
				// 	if (localStorage.getItem(historyKey)) {
						
				// 	}
				// }
				
				const statusText = currentSubmitStatus === 1 ? '一次过磅' : '二次过磅';
				console.log(`${num === '1001' ? '东磅' : '西磅'}：${statusText}提交成功，表单已清空，缓存已删除，等待用户搜索车牌号或实时数据推送`)
				
				
				ElMessage.success(res.data.message)
			} else {
				ElMessage.error(res?.data?.message || '请求失败')
			}
		} catch (error : any) {
			console.error('API请求错误:', error)
			ElMessage.error(error.data.message || '网络请求异常')
		}
	}

	
	// 退出登录
	const goOut = () => {
		ElMessageBox.confirm(
			'您确定要退出登录嘛?',
			'提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(async () => {
			await logout().then(() => {
				ElMessage({ type: 'success', message: '退出成功!' })
				window.location.reload()
			}).catch(err => {
				console.error('退出错误:', err)
				ElMessage({ type: 'error', message: '退出异常:' + err.message })
			})
		}).catch(() => {
			ElMessage({ type: 'info', message: '已取消退出' })
		})
	}

	// 组件激活时检查（路由切换返回时触发）
	onActivated(() => {
		console.log('组件激活，检查是否需要查询历史数据');
		
		// 东磅激活检查 - 只有当前表单为空且有新车牌号时才查询
		const eastActiveLicense = counterStore.persistedData.licensePlates['1001'] || counterStore.eastPound.autoLicense;
		console.log('eastActiveLicense',eastActiveLicense)
		if (eastActiveLicense && 
			eastActiveLicense.trim() && 
			eastActiveLicense !== formAData.autoLicense &&
			(!formAData.autoLicense || formAData.autoLicense.trim() === '')) {
			console.log(`东磅：组件激活检测到新车牌 ${eastActiveLicense}，查询历史数据`);
			checkLicensePlate('1001', eastActiveLicense);
		}

		// 西磅激活检查 - 只有当前表单为空且有新车牌号时才查询
		const westActiveLicense = counterStore.persistedData.licensePlates['1002'] || counterStore.westPound.autoLicense;
		if (westActiveLicense && 
			westActiveLicense.trim() && 
			westActiveLicense !== formBData.autoLicense &&
			(!formBData.autoLicense || formBData.autoLicense.trim() === '')) {
			console.log(`西磅：组件激活检测到新车牌 ${westActiveLicense}，查询历史数据`);
			checkLicensePlate('1002', westActiveLicense);
		}
	});

	// 组件挂载时初始化 - 用户返回页面时读取缓存和Vuex数据
	onMounted(async () => {
		console.log('页面挂载，开始初始化数据');
		
		// 获取货物/厂家列表
		getCargoNameList();
		await Promise.all([getCompanyNameList(1), getCompanyNameList(2)]);

		// 东磅初始化 - 处理缓存和实时数据
		const eastCache = getCacheData('1001');
		console.log('eastCache',eastCache)
		const eastVuexLicense = counterStore.persistedData.licensePlates['1001'] || counterStore.eastPound.autoLicense;
		
		if (eastCache) {
			// 恢复缓存数据
			Object.assign(formAData, eastCache);
			// 同步weightStatus到frontendWeighStatus
			formAData.frontendWeighStatus = eastCache.weightStatus || 0;
			console.log(`东磅：恢复缓存数据，车牌=${eastCache.autoLicense}，状态同步完成`);
		}
		
		// 检查Vuex中是否有新车牌
		if (eastVuexLicense && eastVuexLicense !== formAData.autoLicense) {
			console.log(`东磅：检测到Vuex新车牌 ${eastVuexLicense}，查询历史数据`);
			formAData.autoLicense = eastVuexLicense;
			checkLicensePlate('1001', eastVuexLicense);
		}

		// 西磅初始化 - 处理缓存和实时数据
		const westCache = getCacheData('1002');
		const westVuexLicense = counterStore.persistedData.licensePlates['1002'] || counterStore.westPound.autoLicense;
		
		if (westCache) {
			// 恢复缓存数据
			Object.assign(formBData, westCache);
			// 同步weightStatus到frontendWeighStatus
			formBData.frontendWeighStatus = westCache.weightStatus || 0;
			console.log(`西磅：恢复缓存数据，车牌=${westCache.autoLicense}，状态同步完成`);
		}
		
		// 检查Vuex中是否有新车牌
		if (westVuexLicense && westVuexLicense !== formBData.autoLicense) {
			console.log(`西磅：检测到Vuex新车牌 ${westVuexLicense}，查询历史数据`);
			formBData.autoLicense = westVuexLicense;
			checkLicensePlate('1002', westVuexLicense);
		}

		// 页面可见性变化监听
		const handleVisibilityChange = () => {
			if (document.visibilityState === 'visible') {
				console.log('页面从最小化返回，检查是否需要查询历史数据');
				
				const currentEastLicense = counterStore.persistedData.licensePlates['1001'] || counterStore.eastPound.autoLicense;
				// 只有当前表单为空且有新车牌号时才查询
				if (currentEastLicense && 
					currentEastLicense.trim() && 
					currentEastLicense !== formAData.autoLicense && 
					(!formAData.autoLicense || formAData.autoLicense.trim() === '')) {
					console.log(`东磅：页面返回检测到新车牌 ${currentEastLicense}，查询历史数据`);
					checkLicensePlate('1001', currentEastLicense);
				}
				
				const currentWestLicense = counterStore.persistedData.licensePlates['1002'] || counterStore.westPound.autoLicense;
				// 只有当前表单为空且有新车牌号时才查询
				if (currentWestLicense && 
					currentWestLicense.trim() && 
					currentWestLicense !== formBData.autoLicense && 
					(!formBData.autoLicense || formBData.autoLicense.trim() === '')) {
					console.log(`西磅：页面返回检测到新车牌 ${currentWestLicense}，查询历史数据`);
					checkLicensePlate('1002', currentWestLicense);
				}
			}
		};
		document.addEventListener('visibilitychange', handleVisibilityChange);

		// 页面离开缓存
		const handleBeforeUnload = () => {
			localStorage.setItem(CACHE_CONFIG.getKey('1001'), JSON.stringify({ data: { ...formAData }, timestamp: Date.now() }));
			localStorage.setItem(CACHE_CONFIG.getKey('1002'), JSON.stringify({ data: { ...formBData }, timestamp: Date.now() }));
		};
		window.addEventListener('beforeunload', handleBeforeUnload);

		// 组件卸载时清理
		onBeforeUnmount(() => {
			window.removeEventListener('beforeunload', handleBeforeUnload);
			document.removeEventListener('visibilitychange', handleVisibilityChange);
		});
	});
</script>


<style lang="scss" scoped>
	.indexBox {
		padding: 8px;
		box-sizing: border-box;
		position: relative;

		.title {
			text-align: center;
			font-size: 32px;
			font-weight: 550;
			position: relative;
		}

		.poundBox {
			width: 100%;
			position: absolute;
			left: 50%;
			transform: translateX(-50%);

			.poundCard {
				min-height: 580px;

				.leftBox {
					padding-left: 50px;
					box-sizing: border-box;

					&_name {
						font-size: 28px;
						font-weight: 550;
						margin-bottom: 4px;
					}
				}

				.rightBox {
					padding-left: 50px;
					box-sizing: border-box;

					&_name {
						font-size: 28px;
						font-weight: 550;
						margin-bottom: 4px;
					}
				}
			}
		}

		/* 弹窗样式 */
		.print-dialog .el-dialog__header {
			text-align: center;
			padding: 10px;
			border-bottom: 1px solid #e4e7ed;
		}

		.print-dialog .el-dialog__title {
			font-size: 16px;
			font-weight: bold;
		}

		.print-dialog .el-dialog__body {
			padding: 15px;
		}

		.print-dialog .el-dialog__footer {
			padding: 10px 15px;
			border-top: 1px solid #e4e7ed;
		}

		.dialog-footer {
			text-align: right;
		}

		/* 表格样式 */
		.print-table table {
			width: 100%;
			border-collapse: collapse;
			border: 1px solid #000;
		}

		.print-table td {
			border: 1px solid #000;
			padding: 5px;
		}
	}
</style>